package com.videostreaming.controller;

import com.videostreaming.controller.base.BaseDbController;
import com.gooddies.wiring.annotations.WiringComponent;
import com.videostreaming.data.Video;
import com.videostreaming.data.User;
import com.wiringweb.annotations.Controller;
import com.wiringweb.annotations.UrlBinding;
import com.wiringweb.http.HttpMethod;
import com.wiringweb.parameterprocessor.annotation.QueryParameter;
import com.wiringweb.resolution.ErrorResolution;
import com.wiringweb.resolution.PlainTextResolution;
import com.wiringweb.resolution.Resolution;
import org.apache.commons.lang3.RandomStringUtils;

@Controller
@WiringComponent(singleton = true)
public class PlayController extends BaseDbController {

    @UrlBinding("/getVideoHash\\.html")
    public Resolution getVideoHash() {
        if (getSessionParameter(LOGGED_USER) == null) {
            return new ErrorResolution(403, "Not authentificated");
        }

        User user = (User) getSessionParameter(LOGGED_USER);
        Video pv = getDb().getVideoForUser(user.getId());
        if (pv == null) {
            String videoHash = RandomStringUtils.randomAscii(3);
            pv = new Video();
            pv.setUserId(user.getId());
            pv.setVideoHash(videoHash);
            pv.setPlay(false);
            getDb().insertVideo(pv);
        }

        return new PlainTextResolution(pv.getVideoHash());
    }

    @UrlBinding(httpMethod = HttpMethod.POST, value = "/startPlay\\.html")
    public Resolution startPlay(@QueryParameter("userSecret") String userSecret, @QueryParameter("name") String streamName) {
        System.out.println("Connected");
        User user = getDb().getUserBySecretHash(userSecret);
        if (user == null) {
            return new ErrorResolution(403, "Not authenticated");
        }
        getDb().setVideoStatusForUser(user.getId(), true);
        return new PlainTextResolution("ok");
    }

    @UrlBinding(httpMethod = HttpMethod.POST, value = "/stopPlay\\.html")
    public Resolution stopPlay(@QueryParameter("userSecret") String userSecret) {
        System.out.println("Stop Connected");
        User user = getDb().getUserBySecretHash(userSecret);
        if (user == null) {
            return new ErrorResolution(403, "Not authenticated");
        }
        getDb().setVideoStatusForUser(user.getId(), false);
        return new PlainTextResolution("ok");
    }
}
